<!--
 * 字典数据管理页面
 * 用于管理具体的字典项数据
 -->

<template>
  <div class="dict-data-list-page">
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1>{{ uiData['list-page-header-string'] }}</h1>
          <div class="breadcrumb" v-if="currentDictType">
            <a-breadcrumb>
              <a-breadcrumb-item>
                <router-link to="/admin/sysdicttype">字典类型管理</router-link>
              </a-breadcrumb-item>
              <a-breadcrumb-item>{{ currentDictTypeName || currentDictType }}</a-breadcrumb-item>
            </a-breadcrumb>
          </div>
        </div>
        <div class="dict-type-info" v-if="currentDictType">
          <a-tag color="blue" class="dict-type-tag">{{ currentDictType }}</a-tag>
          <span class="dict-type-name">{{ currentDictTypeName }}</span>
        </div>
      </div>
      <p class="page-description">管理字典类型下的具体数据项，包括标签、值、排序等信息</p>
    </div>

    <a-card>
      <!-- 搜索表单 -->
      <div class="search-form" v-if="showSearchForm">
        <a-form layout="inline" :model="searchParams">
          <a-form-item label="字典类型">
            <a-select 
              v-model:value="searchParams.dictType" 
              placeholder="请选择字典类型"
              allow-clear
              style="width: 220px"
              @change="handleDictTypeChange"
              show-search
              :filter-option="filterDictTypeOption"
            >
              <a-select-option 
                v-for="type in dictTypeOptions" 
                :key="type.dictType" 
                :value="type.dictType"
              >
                {{ type.dictName }}({{ type.dictType }})
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="字典标签">
            <a-input 
              v-model:value="searchParams.dictLabel" 
              placeholder="请输入字典标签"
              allow-clear
              style="width: 150px"
              @press-enter="searchItems"
            />
          </a-form-item>
          <a-form-item label="字典值">
            <a-input 
              v-model:value="searchParams.dictValue" 
              placeholder="请输入字典值"
              allow-clear
              style="width: 150px"
              @press-enter="searchItems"
            />
          </a-form-item>
          <a-form-item label="状态">
            <a-select 
              v-model:value="searchParams.status" 
              placeholder="请选择状态"
              allow-clear
              style="width: 120px"
              @change="searchItems"
            >
              <a-select-option :value="1">启用</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="searchItems">
                <SearchOutlined /> 搜索
              </a-button>
              <a-button @click="resetSearch">
                <ReloadOutlined /> 重置
              </a-button>
              <a-button type="link" @click="toggleSearchForm">
                {{ showSearchForm ? '收起' : '展开' }}
                <UpOutlined v-if="showSearchForm" />
                <DownOutlined v-else />
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <AnyTable
        ref="itemTable"
        :autoLoad="true"
        :dataLoader="loadItemData"
        :tableColumns="tableColumns"
        :searchParams="searchParams"
        :tableScroll="{ x: 'max-content' }"
        tableRowKey="id"
        :rowClassName="getRowClassName"
        @loadComplete="handleLoadComplete"
      >
        <template #tableToolbar>
          <a-space :size="12">
            <a-button type="primary" @click="addItem">
              <PlusOutlined /> {{ uiData['add-button-text'] }}
            </a-button>
            <a-button @click="toggleSearchForm">
              <SearchOutlined /> {{ showSearchForm ? '隐藏搜索' : '显示搜索' }}
            </a-button>
            <a-tooltip :title="flags.enableMockDataMode ? '当前使用Mock数据模式，点击切换到数据库模式' : '当前使用数据库数据模式，点击切换到Mock模式'">
              <a-button
                type="default"
                :class="flags.enableMockDataMode ? 'data-mode-mock' : 'data-mode-db'"
                @click="toggleDataMode"
              >
                {{ flags.enableMockDataMode ? '📝 Mock数据' : '🗄️ 数据库' }}
              </a-button>
            </a-tooltip>
            <a-button @click="refreshTable">
              <ReloadOutlined /> {{ uiData['refresh-button-text'] }}
            </a-button>
            <a-button @click="backToDictType" v-if="currentDictType">
              <ArrowLeftOutlined /> 返回字典类型
            </a-button>
          </a-space>
        </template>
        
        <template #tableCell="{ column, record }">
          <template v-if="column.key === 'dictType'">
            <a-tag color="blue">{{ record.dictType }}</a-tag>
          </template>
          
          <template v-if="column.key === 'dictLabel'">
            <a-tag 
              :color="getTagColor(record.listClass)"
              :class="record.cssClass"
            >
              {{ record.dictLabel }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'dictValue'">
            <code class="dict-value">{{ record.dictValue }}</code>
          </template>
          
          <template v-if="column.key === 'status'">
            <a-switch 
              :checked="record.status === 1"
              @change="(checked) => toggleStatus(record, checked)"
              :checked-children="uiData['status-enabled']"
              :un-checked-children="uiData['status-disabled']"
              size="small"
            />
          </template>
          
          <template v-if="column.key === 'isDefault'">
            <a-switch 
              :checked="record.isDefault === 1"
              @change="(checked) => toggleDefault(record, checked)"
              :checked-children="uiData['default-yes']"
              :un-checked-children="uiData['default-no']"
              size="small"
            />
          </template>
          
          <template v-if="column.key === 'sortOrder'">
            <a-input-number 
              :value="record.sortOrder"
              :min="0"
              :max="9999"
              size="small"
              @change="(value) => updateSortOrder(record, value)"
              style="width: 80px"
              :placeholder="uiData['sort-order-edit-placeholder']"
            />
          </template>
          
          <template v-if="column.key === 'cssClass'">
            <a-tag v-if="record.cssClass" :class="record.cssClass">
              {{ record.cssClass }}
            </a-tag>
            <span v-else class="text-muted">-</span>
          </template>
          
          <template v-if="column.key === 'listClass'">
            <a-tag v-if="record.listClass" :color="getTagColor(record.listClass)">
              {{ record.listClass }}
            </a-tag>
            <span v-else class="text-muted">-</span>
          </template>
          
          <template v-if="column.key === 'createdTime'">
            <span class="time-text">{{ formatDateTime(record.createdTime) }}</span>
          </template>
          
          <template v-if="column.key === 'updatedTime'">
            <span class="time-text">{{ formatDateTime(record.updatedTime) }}</span>
          </template>
          
          <template v-if="column.key === 'op'">
            <a-space>
              <a-button type="link" size="small" @click="viewItem(record)">
                <EyeOutlined /> {{ uiData['detail-button-text'] }}
              </a-button>
              <a-button type="link" size="small" @click="editItem(record)">
                <EditOutlined /> {{ uiData['edit-button-text'] }}
              </a-button>
              <a-button 
                type="link" 
                size="small" 
                danger 
                @click="deleteItem(record)"
              >
                <DeleteOutlined /> {{ uiData['delete-button-text'] }}
              </a-button>
            </a-space>
          </template>
        </template>
      </AnyTable>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <SysDictDataAddOrEditModal
      ref="addOrEditModalRef" 
      :callbackFunc="searchItems"
      :defaultDictType="currentDictType"
    />
    
    <!-- 详情查看弹窗 -->
    <SysDictDataDetailModal ref="detailModalRef" />
  </div>
</template>

<style scoped>
.dict-data-list-page {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.title-section h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #262626;
  font-weight: 600;
}

.breadcrumb {
  margin-bottom: 8px;
}

.dict-type-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dict-type-tag {
  font-family: 'Courier New', monospace;
  font-weight: 500;
}

.dict-type-name {
  color: #666;
  font-size: 14px;
}

.page-description {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.search-form {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.dict-value {
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #d63384;
}

.time-text {
  color: #666;
  font-size: 12px;
}

.text-muted {
  color: #999;
}

/* 数据模式按钮样式 */
.data-mode-mock {
  border-color: #ff7a00 !important;
  color: #ff7a00 !important;
  background-color: #fff7e6 !important;
}

.data-mode-mock:hover {
  border-color: #ff7a00 !important;
  color: #ff7a00 !important;
  background-color: #ffefde !important;
}

.data-mode-db {
  border-color: #52c41a !important;
  color: #52c41a !important;
  background-color: #f6ffed !important;
}

.data-mode-db:hover {
  border-color: #52c41a !important;
  color: #52c41a !important;
  background-color: #eefdde !important;
}

/* 状态开关样式 */
:deep(.ant-switch-checked) {
  background-color: #52c41a;
}

/* 表格行样式 */
:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}

/* 默认值行样式 */
:deep(.ant-table-tbody > tr.default-row > td) {
  background-color: #f0f9ff;
}

:deep(.ant-table-tbody > tr.default-row:hover > td) {
  background-color: #e0f2fe;
}

/* 禁用行样式 */
:deep(.ant-table-tbody > tr.disabled-row > td) {
  background-color: #fafafa;
  color: #999;
}

:deep(.ant-table-tbody > tr.disabled-row:hover > td) {
  background-color: #f0f0f0;
}
</style>

<script lang="ts" setup>
import { ref, reactive, getCurrentInstance, onMounted, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { 
  PlusOutlined, 
  SearchOutlined, 
  ReloadOutlined, 
  UpOutlined, 
  DownOutlined,
  EditOutlined,
  EyeOutlined,
  DeleteOutlined,
  ArrowLeftOutlined
} from '@ant-design/icons-vue';
import { apiSysDictDataFetchList, apiSysDictDataDelete, apiSysDictDataUpdateStatus, apiSysDictDataUpdateSortOrder } from "./api";
import { tableColumns, uiData, flags } from "./data";
import SysDictDataDetailModal from "./detail.vue";
import SysDictDataAddOrEditModal from "./add-or-edit.vue";
import { getMockSysDictTypeData } from "../sysdicttype/mock";
import { 
  mockUpdateSysDictDataStatus, 
  mockSetSysDictDataDefault, 
  mockUpdateSysDictDataSortOrder 
} from "./mock";

const { $AnyMessageBox } = getCurrentInstance()!.appContext.config.globalProperties;
const route = useRoute();
const router = useRouter();

// 搜索参数
const searchParams = reactive<{
  dictType?: string;
  dictLabel?: string;
  dictValue?: string;
  status?: number;
}>({});

// 页面状态
const showSearchForm = ref(true);
const currentDictType = ref<string>('');
const currentDictTypeName = ref<string>('');

// 字典类型选项
const dictTypeOptions = ref<any[]>([]);

// 组件引用
const itemTable = ref();
const addOrEditModalRef = ref();
const detailModalRef = ref();

// 初始化页面
onMounted(() => {
  initializePage();
  loadDictTypeOptions();
});

// 监听路由变化
watch(() => route.query, (newQuery) => {
  if (newQuery.dictType) {
    currentDictType.value = newQuery.dictType as string;
    searchParams.dictType = newQuery.dictType as string;
    // 查找字典类型名称
    const dictType = dictTypeOptions.value.find(item => item.dictType === newQuery.dictType);
    if (dictType) {
      currentDictTypeName.value = dictType.dictName;
    }
  }
}, { immediate: true });

// 初始化页面
function initializePage() {
  // 从路由参数获取字典类型
  if (route.query.dictType) {
    currentDictType.value = route.query.dictType as string;
    searchParams.dictType = route.query.dictType as string;
  }
}

// 加载字典类型选项
function loadDictTypeOptions() {
  try {
    const response = getMockSysDictTypeData({ status: 1 }); // 只获取启用的字典类型
    dictTypeOptions.value = response.records || [];
    
    // 如果有当前字典类型，查找对应的名称
    if (currentDictType.value) {
      const dictType = dictTypeOptions.value.find(item => item.dictType === currentDictType.value);
      if (dictType) {
        currentDictTypeName.value = dictType.dictName;
      }
    }
  } catch (error) {
    console.error('Failed to load dict type options:', error);
    dictTypeOptions.value = [];
  }
}

// 加载数据
async function loadItemData(params: any) {
  try {
    const response = await apiSysDictDataFetchList(params);
    return response.data;
  } catch (error) {
    console.error('Failed to load item data:', error);
    return { records: [], total: 0 };
  }
}

// 加载完成回调
function handleLoadComplete() {
  console.log('Dictionary data loaded successfully');
}

// 搜索功能
function searchItems() {
  itemTable.value?.refreshTable(true);
}

// 重置搜索
function resetSearch() {
  Object.keys(searchParams).forEach(key => {
    delete searchParams[key as keyof typeof searchParams];
  });
  currentDictType.value = '';
  currentDictTypeName.value = '';
  itemTable.value?.resetTable();
}

// 切换搜索表单显示
function toggleSearchForm() {
  showSearchForm.value = !showSearchForm.value;
}

// 字典类型筛选选项过滤
function filterDictTypeOption(input: string, option: any) {
  const text = `${option.children}`.toLowerCase();
  return text.includes(input.toLowerCase());
}

// 处理字典类型变化
function handleDictTypeChange(value: string) {
  if (value) {
    const dictType = dictTypeOptions.value.find(item => item.dictType === value);
    if (dictType) {
      currentDictType.value = value;
      currentDictTypeName.value = dictType.dictName;
    }
  } else {
    currentDictType.value = '';
    currentDictTypeName.value = '';
  }
  searchItems();
}

// 刷新表格
function refreshTable() {
  itemTable.value?.refreshTable();
}

// 切换数据模式
function toggleDataMode() {
  flags.enableMockDataMode = !flags.enableMockDataMode;
  $AnyMessageBox.message.info(
    flags.enableMockDataMode ? '已切换到Mock数据模式' : '已切换到数据库模式'
  );
  refreshTable();
}

// 返回字典类型管理
function backToDictType() {
  router.push('/admin/sysdicttype');
}

// 获取标签颜色
function getTagColor(listClass: string): string {
  const colorMap: Record<string, string> = {
    'success': 'success',
    'primary': 'processing',
    'warning': 'warning',
    'danger': 'error',
    'processing': 'processing',
    'pink': 'magenta',
    'default': 'default'
  };
  return colorMap[listClass] || 'default';
}

// 格式化日期时间
function formatDateTime(dateTime: string): string {
  if (!dateTime) return '-';
  return dateTime;
}

// 获取行样式类名
function getRowClassName(record: any): string {
  const classNames = [];
  
  // 默认值行样式
  if (record.isDefault === 1) {
    classNames.push('default-row');
  }
  
  // 禁用行样式
  if (record.status === 0) {
    classNames.push('disabled-row');
  }
  
  return classNames.join(' ');
}

// 状态切换
async function toggleStatus(record: any, checked: boolean) {
  try {
    const newStatus = checked ? 1 : 0;
    
    if (flags.enableMockDataMode) {
      mockUpdateSysDictDataStatus(record.id, newStatus);
    } else {
      // 调用真实API
      await apiSysDictDataUpdateStatus(record.id, newStatus);
    }
    
    record.status = newStatus;
    $AnyMessageBox.message.success(
      checked ? uiData['status-enabled'] + '成功' : uiData['status-disabled'] + '成功'
    );
  } catch (error) {
    console.error('Failed to toggle status:', error);
    $AnyMessageBox.message.error(uiData['operation-failed']);
  }
}

// 切换默认值
async function toggleDefault(record: any, checked: boolean) {
  try {
    if (checked) {
      if (flags.enableMockDataMode) {
        mockSetSysDictDataDefault(record.id);
      } else {
        // 调用真实API
        // await apiSetSysDictDataDefault(record.id);
      }
      
      // 刷新表格以更新其他行的默认值状态
      refreshTable();
      $AnyMessageBox.message.success('设置默认值成功');
    } else {
      // 取消默认值
      record.isDefault = 0;
      $AnyMessageBox.message.success('取消默认值成功');
    }
  } catch (error) {
    console.error('Failed to toggle default:', error);
    $AnyMessageBox.message.error(uiData['operation-failed']);
  }
}

// 更新排序
async function updateSortOrder(record: any, value: number) {
  if (value === null || value === undefined) return;
  
  try {
    if (flags.enableMockDataMode) {
      mockUpdateSysDictDataSortOrder(record.id, value);
    } else {
      // 调用真实API
      await apiSysDictDataUpdateSortOrder(record.id, value);
    }
    
    record.sortOrder = value;
    $AnyMessageBox.message.success('排序更新成功');
  } catch (error) {
    console.error('Failed to update sort order:', error);
    $AnyMessageBox.message.error(uiData['operation-failed']);
  }
}

// CRUD操作
function addItem() {
  console.log('addItem clicked');
  console.log('addOrEditModalRef.value:', addOrEditModalRef.value);
  console.log('currentDictType.value:', currentDictType.value);
  
  if (addOrEditModalRef.value) {
    console.log('Calling showAdd...');
    addOrEditModalRef.value.showAdd(currentDictType.value);
  } else {
    console.error('addOrEditModalRef is null');
  }
}

function editItem(item: any) {
  console.log('editItem clicked', item);
  console.log('item.id:', item.id, 'type:', typeof item.id);
  console.log('addOrEditModalRef.value:', addOrEditModalRef.value);
  
  if (addOrEditModalRef.value) {
    console.log('Calling showEdit...');
    // 确保ID是数字类型
    const id = typeof item.id === 'string' ? parseInt(item.id, 10) : item.id;
    console.log('Converted id:', id, 'type:', typeof id);
    addOrEditModalRef.value.showEdit(id);
  } else {
    console.error('addOrEditModalRef is null');
  }
}

function viewItem(item: any) {
  console.log('viewItem clicked', item);
  console.log('detailModalRef.value:', detailModalRef.value);
  
  if (detailModalRef.value) {
    console.log('Calling openModal...');
    detailModalRef.value.openModal(item);
  } else {
    console.error('detailModalRef is null');
  }
}

function deleteItem(item: any) {
  $AnyMessageBox.confirmDanger(
    uiData['confirm-delete-title'], 
    uiData['confirm-delete-content'], 
    () => {
      apiSysDictDataDelete(item.id).then(() => {
        $AnyMessageBox.message.success(uiData['operation-success']);
        searchItems();
      }).catch((error) => {
        console.error('Failed to delete item:', error);
        $AnyMessageBox.message.error(uiData['operation-failed']);
      });
    }
  );
}
</script>